package com.example.chengzhengwei;

import android.app.ProgressDialog;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.example.chengzhengwei.utils.SpectrophotometerProtocol;

import java.text.DecimalFormat;

public class SettingsActivity extends AppCompatActivity {

    private EditText editTextTemperature, editTextTimeMinutes, editTextTimeSeconds, editTextFluorescencePeriod;
    private DatabaseHelper dbHelper;

    private SerialApp serialApp;
    private ProgressDialog progressDialog; // 添加进度对话框

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_settings);

        serialApp = (SerialApp) getApplication();
        dbHelper = new DatabaseHelper(this);

        editTextTemperature = findViewById(R.id.editTextTemperature);
        editTextTimeMinutes = findViewById(R.id.editTextTimeMinutes);
        editTextTimeSeconds = findViewById(R.id.editTextTimeSeconds);
        editTextFluorescencePeriod = findViewById(R.id.editTextFluorescencePeriod);

        Button buttonConfirm = findViewById(R.id.buttonConfirm);
        Button buttonCancel = findViewById(R.id.buttonCancel);

        buttonConfirm.setOnClickListener(v -> {
            if (validateInputs()) {
                setParameters();
            }
        });

        buttonCancel.setOnClickListener(v -> {
            finish();
        });

        loadSavedData();
    }

    // 显示进度对话框
    private void showProgressDialog() {
        runOnUiThread(() -> {
            progressDialog = new ProgressDialog(this);
            progressDialog.setMessage("正在设置...");
            progressDialog.setCancelable(false); // 不可取消
            progressDialog.show();
        });
    }

    // 隐藏进度对话框
    private void dismissProgressDialog() {
        runOnUiThread(() -> {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        });
    }

    private void loadSavedData() {
        Cursor cursor = dbHelper.getAllData();
        if (cursor != null && cursor.moveToFirst()) {
            int temperatureIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_TEMPERATURE);
            int timeMinutesIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_TIME_MINUTES);
            int timeSecondsIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_TIME_SECONDS);
            int fluorescencePeriodIndex = cursor.getColumnIndex(DatabaseHelper.COLUMN_FLUORESCENCE_PERIOD);

            if (temperatureIndex != -1) {
                double temperature = cursor.getDouble(temperatureIndex);
                editTextTemperature.setText(new DecimalFormat("#.#").format(temperature));
            }
            if (timeMinutesIndex != -1) {
                int timeMinutes = cursor.getInt(timeMinutesIndex);
                editTextTimeMinutes.setText(String.valueOf(timeMinutes));
            }
            if (timeSecondsIndex != -1) {
                int timeSeconds = cursor.getInt(timeSecondsIndex);
                editTextTimeSeconds.setText(String.valueOf(timeSeconds));
            }
            if (fluorescencePeriodIndex != -1) {
                int fluorescencePeriod = cursor.getInt(fluorescencePeriodIndex);
                editTextFluorescencePeriod.setText(String.valueOf(fluorescencePeriod));
            }

            cursor.close();
        }
    }


    private boolean validateInputs() {
        // 检查温度输入
        if (editTextTemperature.getText().toString().isEmpty()) {
            showToast("请输入温度值");
            return false;
        }

        // 检查时间输入（分钟和秒）
        if (editTextTimeMinutes.getText().toString().isEmpty() &&
                editTextTimeSeconds.getText().toString().isEmpty()) {
            showToast("请输入时间（分钟或秒）");
            return false;
        }

        // 检查荧光周期
        if (editTextFluorescencePeriod.getText().toString().isEmpty()) {
            showToast("请输入荧光周期");
            return false;
        }

        return true;
    }

    private void setParameters() {
        // 获取输入值
        double temperature = Double.parseDouble(editTextTemperature.getText().toString());
        int minutes = editTextTimeMinutes.getText().toString().isEmpty() ? 0 :
                Integer.parseInt(editTextTimeMinutes.getText().toString());
        int seconds = editTextTimeSeconds.getText().toString().isEmpty() ? 0 :
                Integer.parseInt(editTextTimeSeconds.getText().toString());
        int fluorescencePeriod = Integer.parseInt(editTextFluorescencePeriod.getText().toString())*1000;

        // 将分钟和秒转换为总秒数
        int totalSeconds = (minutes * 60 + seconds);

        // 温度转换为整数（乘以100，保留两位小数）
        int temperatureInt = (int) (temperature * 100);

        // 构建设置参数命令
        byte[] command = SpectrophotometerProtocol.buildSetParamsCommand(
                SpectrophotometerProtocol.PC_ADDRESS,
                temperatureInt,
                totalSeconds,
                fluorescencePeriod
        );

        // 通过串口发送命令
        serialApp.safeWrite(command, new SerialApp.SerialWriteCallback() {
            @Override
            public void onWriteComplete(int bytesWritten) {
                // 写入成功后开始读取响应
//                serialApp.recycleReading(new SerialApp.SerialReadCallback() {
//                    @Override
//                    public void onDataReceived(byte[] data) {
//                        handleResponse(data);
//                    }
//                    @Override
//                    public void onReadError(Exception e) {
//                        dismissProgressDialog(); // 读取错误时关闭对话框
//                        runOnUiThread(() -> {
//                            showToast("读取响应失败: " + e.getMessage());
//                        });
//                    }
//                });
            }

            @Override
            public void onWriteError(Exception e) {
                dismissProgressDialog(); // 读取错误时关闭对话框
                runOnUiThread(() -> {
                    showToast("发送命令失败: " + e.getMessage());
                });
            }
        });
    }

    private void handleResponse(byte[] data) {
        try {
            SpectrophotometerProtocol.Response response = SpectrophotometerProtocol.parseResponse(data);
            // 检查是否是设置参数响应
            if (response.getCommand() == SpectrophotometerProtocol.RESP_SET_PARAMS) {
                dismissProgressDialog(); // 关闭对话框
                runOnUiThread(() -> {
                    if (response.isSetParamsSuccessful()) {
                        // 保存参数到数据库
                        saveParametersToDatabase();

                        // 跳转到运行界面
                        Intent intent = new Intent(SettingsActivity.this, EnterTestActivity.class);
                        startActivity(intent);
                        finish();
                        showToast("参数设置成功");
                    } else {
                        showToast("参数设置失败");
                    }
                });
            } else {
                dismissProgressDialog(); // 关闭对话框
                runOnUiThread(() -> {
                    showToast("收到非预期响应: " + String.format("0x%02X", response.getCommand()));
                });
            }
        } catch (SpectrophotometerProtocol.ProtocolException e) {
            dismissProgressDialog(); // 关闭对话框
            runOnUiThread(() -> {
                showToast("协议解析错误: " + e.getMessage());
            });
        }
    }

    private void saveParametersToDatabase() {
        // 获取输入值
        double temperature = Double.parseDouble(editTextTemperature.getText().toString());
        int minutes = editTextTimeMinutes.getText().toString().isEmpty() ? 0 :
                Integer.parseInt(editTextTimeMinutes.getText().toString());
        int seconds = editTextTimeSeconds.getText().toString().isEmpty() ? 0 :
                Integer.parseInt(editTextTimeSeconds.getText().toString());
        int fluorescencePeriod = Integer.parseInt(editTextFluorescencePeriod.getText().toString());

        // 保存到数据库
        dbHelper.saveParameters(temperature, minutes, seconds, fluorescencePeriod);
    }

    private void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_LONG).show();
    }

    private void unregisterRecycleReading(){
        if (mSettingReadCallback != null) {
            //serialApp.unregisterRecycleReading(mSettingReadCallback);
            mSettingReadCallback = null;
        }
    }

    private void registerRecycleReading(){
        if(mSettingReadCallback==null){
            // 创建并注册回调
            mSettingReadCallback = new SerialApp.SerialReadCallback() {
                @Override
                public void onDataReceived(byte[] data) {
                    handleResponse(data);
                }

                @Override
                public void onReadError(Exception e) {
                    runOnUiThread(() -> {
//                        progressDialog.dismiss();
                        Toast.makeText(SettingsActivity.this,
                                "读取自检响应失败: " + e.getMessage(),
                                Toast.LENGTH_LONG).show();
                    });
                }
            };
        }
        // 注册回调
        //serialApp.recycleReading(mSettingReadCallback);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerRecycleReading();
    }

    @Override
    protected void onStop() {
        super.onStop();
        // 取消注册回调
        unregisterRecycleReading();
    }

    private SerialApp.SerialReadCallback mSettingReadCallback;

}